﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using Microsoft.SharePoint;
using Slam;
using Slam.Configuration;
using SlamCms.Common;
using SlamCms.Configuration;
using SlamCms.SharePoint.Publishing.Data;
using Microsoft.SharePoint.WebControls;
using SlamCms.SharePoint.Publishing.Services;

namespace SlamCms.SharePoint.Publishing.Pages
{
	public partial class Redirector : LayoutsPageBase
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (Request.QueryString["to"] == null)
				throw new Exception("Error. No 'to' parameter passed in querystring to sharepoint redirector. Need someplace to redirect to.");

			Redirect(Request.QueryString["to"]);
		}

		protected void Redirect(string redirectType)
		{
			switch (redirectType.ToLower())
			{
				case Constants.RedirectDestinations.Document:
					if (Request.QueryString["slamId"] != null && Request.QueryString["version"] != null)
						RedirectionService.RedirectToDocument(Request.QueryString["slamId"], Request.QueryString["version"].Equals("live", StringComparison.OrdinalIgnoreCase));
					else if (Request.QueryString["slamId"] != null)
						RedirectionService.RedirectToDocument(Request.QueryString["slamId"]);
					break;
				case Constants.RedirectDestinations.EditForm:
					if (Request.QueryString["slamId"] != null && Request.QueryString["returnUrl"] != null)	RedirectionService.RedirectToEditForm(Request.QueryString["slamId"], Request.QueryString["returnUrl"]);
					else if (Request.QueryString["slamId"] != null)											RedirectionService.RedirectToEditForm(Request.QueryString["slamId"]);
					else																					throw new Exception("Error. No slam id passed in querystring to sharepoint edit form redirector.");
					break;
				case Constants.RedirectDestinations.FrontEnd:
					Response.Redirect(Request.QueryString["ReturnUrl"] == null ? ConfigurationManager.Environment.DefaultApplication.FrontEndUrl : (Request.QueryString["ReturnUrl"].Contains("http") ? Request.QueryString["ReturnUrl"] : ConfigurationManager.Environment.DefaultApplication.FrontEndUrl.TrimEnd('/') + "/" + Request.QueryString["ReturnUrl"].TrimStart('/')));
					break;
				default:
					throw new Exception("Content item redirect failed for user {0} and content item {1}".F(SPContext.Current.Web.CurrentUser != null ? SPContext.Current.Web.CurrentUser.Name : "", Request.QueryString["slamId"]));
			}
		}
	}
}
